package com.zxk.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.zxk.app.vo.AppStartVo;
import com.zxk.constant.JNAConstants;
import com.zxk.constant.PicConstants;
import com.zxk.entity.TaskConfig;
import com.zxk.handler.TaskHandler;
import com.zxk.util.HwndUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 主程序入口
 *
 * @author: 舟小亢
 * @date: 2023-07-18 22:20
 */
public class StartController {

    private static Logger LOG = LoggerFactory.getLogger(StartController.class);

    public static ExecutorService executorService = Executors.newFixedThreadPool(10);

    /**
     * 程序入口
     */
    public static void run() {
        LOG.info("选择的任务:{}", AppStartVo.TASK_MAP.values());
        // 初始化文件夹
        initDir();
        // 导入第三方库
        loadOpenCV_new();
        // 查找句柄并开启任务
        startHwnd();
    }

    private static void initConfig(String[] args) {
        LOG.info("入参大小{},入参: {}", args.length, Arrays.toString(args));
        // 默认配置
        if (args.length == 0) {
            LOG.info("入参为空，启动默认配置");
            return;
        }
        Map<String, String> hm = new HashMap<>();
        for (int i = 0; i < args.length; i++) {
            String taskInfo = args[i];
            hm.put(taskInfo.split("&")[0], taskInfo.split("&")[1]);
        }
        TaskConfig.loginTask = Boolean.parseBoolean(hm.get("loginTask") == null ? "false" : hm.get("loginTask"));
        TaskConfig.singleTask = Boolean.parseBoolean(hm.get("singleTask") == null ? "false" : hm.get("singleTask"));
        TaskConfig.teamTask = Boolean.parseBoolean(hm.get("teamTask") == null ? "false" : hm.get("teamTask"));
        TaskConfig.ghostTask = Boolean.parseBoolean(hm.get("ghostTask") == null ? "false" : hm.get("ghostTask"));
        TaskConfig.myTask = hm.get("myTask");
        TaskConfig.useVigor = Boolean.parseBoolean(hm.get("useVigor") == null ? "false" : hm.get("useVigor"));

        TaskConfig.printTaskInfo();
    }


    /**
     * 查找句柄并开启任务
     */
    private static void startHwnd() {
        Map<String, WinDef.HWND> hwnds = HwndUtil.getStartHwnds(JNAConstants.HANDLE_0);
        if (CollectionUtil.isEmpty(hwnds)) {
            return;
        }
        int cnt = 0;
        int intervalX = 100;
        int intervalY = 50;
        for (Map.Entry<String, WinDef.HWND> hwndEntry : hwnds.entrySet()) {
            String hwndName = hwndEntry.getKey();
            WinDef.HWND hwnd_0 = hwndEntry.getValue();
            WinDef.HWND hwnd_1 = User32.INSTANCE.FindWindowEx(hwnd_0, null, null, JNAConstants.HANDLE_1);
            WinDef.HWND hwnd_2 = User32.INSTANCE.FindWindowEx(hwnd_1, null, null, JNAConstants.HANDLE_2);
            executorService.execute(new TaskHandler(hwnd_0, hwnd_1, hwnd_2, 0 + intervalX * cnt, 0 + intervalY * cnt, hwndName));
            LOG.info("开启第[{}]个线程,线程名[{}]", ++cnt, hwndName);
        }
    }

    /**
     * 初始化文件夹参数
     */
    public static void initDir() {
        // 初始化文件夹
        File file = new File(PicConstants.TEMP_PIC_PATH);
        if (file.exists()) {
            boolean del = FileUtil.del(file);
            System.out.println("清空文件夹：" + del);
        }
        file.mkdirs();
    }

    /**
     * 导入Opencv库
     */
    public static void loadOpenCV() {
        URL url = ClassLoader.getSystemResource("");
        String path = url.getPath();
        System.out.println("路径是:" + path + "结束");
        System.load(path);
    }

    /**
     * 导入Opencv库
     */
    public static void loadOpenCV_new() {
        String currentDirectory = System.getProperty("user.dir") + File.separator + "otherResources/opencv_java460.dll";
        LOG.info("Opencv路径是:{}", currentDirectory);
        System.load(currentDirectory);
        LOG.info("Opencv加载成功！");
    }

    /**
     * 导入Opencv库
     */
    public static void loadOpenCV_1() {
        URI uri = null;
        try {
            uri = StartController.class.getResource("/otherResources/opencv_java460.dll").toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        String realPath = new File(uri).getAbsolutePath();
        System.out.println("路径是:" + realPath + "结束");
        System.load(realPath);
    }


    /**
     * 导入Opencv库
     */
    public static void loadOpenCV_2() {
        System.loadLibrary("/opencv_java460");
    }


}
